package cn.bytecollege.admin.filter;

import cn.bytecollege.common.constant.Resource;
import cn.bytecollege.common.entity.Category;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "CategoryFilter", servletNames = {"CategoryAddController","CategoryUpdateController"})
public class CategoryFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        String method = req.getMethod();
        if(method.equalsIgnoreCase("post")){
            String categoryName = req.getParameter("categoryName");
            if(categoryName == null || categoryName.equals("")){
                String msg = "请填写分类";
                request.setAttribute("msg",msg);
                if(uri.contains("categoryAdd")){
                    request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/categoryAdd.jsp")
                            .forward(request,response);
                }else  if(uri.contains("categoryUpdate")){
                    String id = req.getParameter("id");

                    Category tempCategory = new Category();
                    tempCategory.setCategoryId(Integer.valueOf(id));
                    tempCategory.setCategoryName(categoryName);

                    request.setAttribute("category",tempCategory);
                    request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/categoryUpdate.jsp")
                            .forward(request,response);
                }
                return;
            }
            chain.doFilter(request,response);
            return;
        }
        chain.doFilter(request, response);
    }
}
